import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {Button, Form, Icon, Modal, Upload} from 'antd';
@connect(({ versionMag, loading }) => ({
  versionMag,
  loading: loading.models.versionMag,
}))
@Form.create()
class UploadFileForm extends PureComponent {
  state = {
    fileList: [],
    uploading: false,
  }
  doUpload = () => {
    const { dispatch, setPath } = this.props;
    const { fileList } = this.state;
    if (fileList && fileList.length > 1) {
      Modal.warning({title: "一次最多上传1个文件"});
      return;
    }
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('file', file);
    });
    this.setState({
      uploading: true,
    });
    dispatch({
      type: 'versionMag/getUpload',
      payload: formData,
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            // fileList: [],
            uploading: false,
          });
          Modal.success({title: res.msg});
          setPath(res.data)
        } else {
          this.setState({
            uploading: false,
          });
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  render() {
    const { form } = this.props;
    const {uploading, fileList} = this.state;
    let title = '上传文件';

    const props = {
      onRemove: (file) => {
        this.setState((state) => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };

    return (
      <div>
        <Upload {...props}>
          <Button disabled={uploading}>
            <Icon type="upload"/> 选择文件
          </Button>
        </Upload>
        <Button
          type="primary"
          onClick={this.doUpload}
          disabled={fileList.length === 0}
          loading={uploading}
          style={{marginTop: 16}}
        >
          {uploading ? '上传中' : '上传升级包'}
        </Button>
      </div>
    );
  }
}

export default UploadFileForm;
